<template>
  <div class="setting-container">
    <!-- 设置padding -->
    <div class="app-container">
      <el-card v-loading="loading">
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="role">

            <!-- 添加角色的按钮 -->
            <el-button type="primary" size="small" @click="showDialog = true"> + 新增角色</el-button>

            <!-- 角色表格 -->
            <el-table :data="data" class="role-table">
              <el-table-column label="序号" width="100" type="index" :index="indexMethod" />
              <el-table-column prop="name" label="角色名称" width="180" />
              <el-table-column prop="description" label="描述" />
              <el-table-column prop="name" label="操作" width="250">

                <template #default="{ row }">
                  <el-button type="success" size="mini" @click="clickAssign(row.id)">分配权限</el-button>
                  <el-button type="primary" size="mini" @click="edit(row.id)">编辑</el-button>
                  <el-button type="danger" size="mini" @click="del(row.id)">删除</el-button>
                </template>

              </el-table-column>
            </el-table>

            <!-- 角色分页 -->
            <!--
              current-page:当前页码值
              page-sizes: 设置每页显示的条数
              page-size:当前页显示的条数
              layout:显示的版块
              total:数据的总条数

              @size-change:修改每页条数事件
              @current-change:条码改变时事件
             -->
            <el-pagination
              :current-page="page"
              :page-sizes="[1, 2, 3, 4, 5]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />

          </el-tab-pane>

          <el-tab-pane label="公司信息" name="company">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <!-- 添加编辑角色弹出框 -->
      <el-dialog :title="showTitle" :visible="showDialog" @close="handleClose">
        <!-- model   rules   prop     v-model -->
        <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="form.description" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="clickSubmit">确定</el-button>
        </template>
      </el-dialog>

      <!-- 角色分配权限弹出框 -->
      <el-dialog
        title="分配权限"
        :visible="showAssignDialog"
        @close="closeAssignDialog"
        @open="openAssignDialog"
      >
        <!-- 树状控件 -->
        <el-tree
          ref="tree"
          :data="permissionTree"
          :props="{label:'name'}"
          show-checkbox
          default-expand-all
          node-key="id"
          check-strictly
        />

        <template #footer>
          <div style="text-align: right;">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click="clickAssignSubmit">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { reqGetPermissionList } from '@/api/permission'
import { reqGetRoles, reqDelRole, reqAddRole, reqGetRoleById, reqUpdateRole, reqAssignPermission } from '@/api/setting'
import { reqGetCompanyById } from '@/api/company'
import { mapState } from 'vuex'
import { transListDataToTreeData } from '@/utils'

export default {
  name: 'Settings',
  data() {
    return {
      activeName: 'role',
      data: [],
      page: 1,
      pagesize: 3,
      total: 0,

      showDialog: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: ['blur', 'change'] }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: ['blur', 'change'] }
        ]
      },

      companyForm: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      },

      loading: false,

      showAssignDialog: false,

      permissionTree: [],

      roleId: ''
    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    showTitle() {
      return this.form.id ? '编辑角色' : '新增角色'
    }
  },
  created() {
    this.getRoles()
    this.getCompanyInfo()
  },
  methods: {
    async getRoles() {
      this.loading = true

      const { data: { rows, total }} = await reqGetRoles(this.page, this.pagesize)
      this.data = rows
      this.total = total

      this.loading = false
    },
    handleSizeChange(newSize) {
      // 1.修改每页显示的条数
      this.pagesize = newSize
      this.page = 1
      // 2.重新获取角色数据
      this.getRoles()
    },
    handleCurrentChange(newPage) {
      // 1.修改当前页码值
      this.page = newPage
      // 2.重新获取角色数据
      this.getRoles()
    },
    // 自定义序号
    indexMethod(index) {
      return index + 1 + (this.page - 1) * this.pagesize
    },
    // 根据id删除角色
    async del(id) {
      try {
        await this.$confirm('确定删除该角色吗', '友情提示')
        await reqDelRole(id)
        this.$message.success('删除角色成功')

        // 条数及页码判断
        if (this.data.length === 1 && this.page !== 1) {
          this.page--
        }

        this.getRoles()
      } catch (err) {
        console.log(err)
      }
    },
    // 关闭弹出框
    handleClose() {
      this.showDialog = false
      this.$refs.roleForm.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    // 新添或更新角色
    clickSubmit() {
      this.$refs.roleForm.validate(async flag => {
        if (!flag) return

        if (this.form.id) {
          // 更新
          await reqUpdateRole(this.form)
          this.$message.success('更新角色成功')
        } else {
          // 添加
          await reqAddRole(this.form)
          this.$message.success('新增角色成功')
        }

        this.handleClose()
        this.getRoles()
      })
    },
    // 编辑角色
    async edit(id) {
      this.showDialog = true

      const { data } = await reqGetRoleById(id)
      this.form = data
    },
    // 获取公司信息
    async getCompanyInfo() {
      const { data } = await reqGetCompanyById(this.userInfo.companyId)
      this.companyForm = data
    },

    // 关闭权限分配的弹出框
    closeAssignDialog() {
      this.showAssignDialog = false

      // 清空树上已经有的权限
      this.$refs.tree.setCheckedKeys([])
    },
    // 点击显示权限弹出框
    clickAssign(id) {
      this.showAssignDialog = true

      this.roleId = id
    },

    async openAssignDialog() {
      // 1.获取所有的权限数据
      const { data } = await reqGetPermissionList()
      this.permissionTree = transListDataToTreeData(data, '0')

      // 2.获取当前角色实现已有的权限数据的回显
      const { data: { permIds }} = await reqGetRoleById(this.roleId)
      // console.log(permIds)
      this.$refs.tree.setCheckedKeys(permIds)
    },
    // 给当前角色重新设置权限
    async clickAssignSubmit() {
      const permIds = this.$refs.tree.getCheckedKeys()
      await reqAssignPermission(this.roleId, permIds)
      this.$message.success('添加权限成功')
      this.closeAssignDialog()
    }
  }
}
</script>

<style lang="scss" scoped>
.role-table{
  margin:10px 0!important;
}

</style>
